package xsource

import (
	"time"

	"gitee.com/xiaoyutab/xgotool/optional/xcache"
	"gitee.com/xiaoyutab/xgotool/optional/xlog"
	"gitee.com/xiaoyutab/xgotool/xerror"
)

// 创建批次信息
//
//	source	待创建的批次信息
func Create(source *Source) error {
	if source.UserId == 0 {
		return xerror.New("创建用户不能为空")
	}
	if _default.DB == nil {
		return xerror.New("数据库未连接")
	}
	source.UpdatedAt = time.Now().Format(time.DateTime)
	if source.CreatedAt == "" {
		source.CreatedAt = time.Now().Format(time.DateTime)
	}
	// 入库存储
	err := _default.DB.Save(source).Error
	if err != nil {
		return xlog.EE("溯源批次信息存储失败", err)
	}
	xcache.SetStruct(xcache.Key("xsource.info", source.ID), source)
	return nil
}
